﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Security.Cryptography;

namespace mamnontuoitho7.AppCode
{   
    /// <summary>
    /// use for contain the authorized user
    /// </summary>
    public class MemberObjectForAuthorrization 
    {
        public string MemberID { get; set; }
        public string username {get ; set; }
        public string Fullname {get ; set; }
        public int RoleID { get; set; }
        public string Avatar { get; set; }
        public string ClassID { get; set; }
        public bool MemberVisible { get; set; }
        private bool isAuthorized = false;
        public bool IsAuthorized {
            get { return isAuthorized; }
            set { isAuthorized = value; }
        }
    }



    public class Member
    {
        public ConnectGetData _connectData;
        private General _general = new General();

        public Member() {
            _connectData = new ConnectGetData();
       //   _cmd = new SqlCommand(_sql, _connectData.GetConnect());
        }



        /// <summary>
        /// to authorize the user, if they are member or not.
        /// </summary>
        /// <param name="username"></param> 
        /// <param name="password"></param>
        /// <returns></returns>
        public MemberObjectForAuthorrization checkLogin(String username, String password)
        {
            //bool flag = false;
            MemberObjectForAuthorrization memObj = new MemberObjectForAuthorrization();
            try
            {
               string sql = "select * from Member where MemberName=@username and Pass=@Password";

               SqlCommand cmd = new SqlCommand(sql, _connectData.GetConnect());
               cmd.Parameters.AddWithValue("@username", username);
               cmd.Parameters.AddWithValue("@Password", password);
               DataTable dt = _connectData.GetDataTable(cmd);
               if (dt.Rows.Count > 0) {
                   memObj.MemberID = dt.Rows[0]["MemberID"].ToString();
                   memObj.username = dt.Rows[0]["MemberName"].ToString();
                   memObj.Fullname = dt.Rows[0]["FullName"].ToString();
                   memObj.RoleID   = Convert.ToInt16(dt.Rows[0]["RoleID"]);
                   memObj.Avatar   = dt.Rows[0]["Avatar"].ToString();
                   memObj.ClassID  = dt.Rows[0]["ClassID"].ToString();
                   memObj.MemberVisible = Convert.ToBoolean(dt.Rows[0]["MemberVisible"]);
                   memObj.IsAuthorized = true;                  
               }
               cmd.Dispose();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("Error error error: " + ex.StackTrace);
                return memObj;
            }
            return memObj;
        }



        /// <summary>
        /// Create Member (Teacher, Parent, Principal, Admin)
        /// </summary>
        /// <param name="roleID"></param>
        /// <param name="memberName"></param>
        /// <param name="pass"></param>
        /// <param name="fullName"></param>
        /// <param name="sex"></param>
        /// <param name="birthday"></param>
        /// <param name="address"></param>
        /// <param name="email"></param>
        /// <param name="phone"></param>
        /// <param name="avatar"></param>
        /// <param name="career"></param>
        /// <returns></returns>
        public bool MemberCreate(int roleID, String memberName, String pass, String fullName, int sex, String birthday, String address, String email, String phone, String avatar, String career)
        {

            try
            {
                string sqlUp = "Insert into Member(RoleID, MemberName, Pass, FullName, Sex,Birthday, Address, Email, Phone, Avatar, Career ) values(@RoleID, @MemberName, @Pass, @FullName, @Sex, @Birthday, @Address, @Email, @Phone, @Avatar, @Career)";
                SqlCommand cmd = new SqlCommand(sqlUp, _connectData.GetConnect());
                cmd.Parameters.AddWithValue("@RoleID", roleID);
                cmd.Parameters.AddWithValue("@MemberName", memberName);
                cmd.Parameters.AddWithValue("@Pass", pass);
                cmd.Parameters.AddWithValue("@FullName", fullName);
                cmd.Parameters.AddWithValue("@Sex", sex);
                cmd.Parameters.AddWithValue("@Birthday", birthday);
                cmd.Parameters.AddWithValue("@Address", address);
                cmd.Parameters.AddWithValue("@Email", email);
                cmd.Parameters.AddWithValue("@Phone", phone);
                cmd.Parameters.AddWithValue("@Avatar", avatar);
                cmd.Parameters.AddWithValue("@Career", career);

                cmd.ExecuteNonQuery();
                cmd.Dispose();

            }
            catch (Exception ex)
            {

                System.Console.WriteLine("Co loiiii: " + ex.StackTrace);
                return false;
            }
            return true;
        }


        /// <summary>
        /// check the current role if it is authorized or not
        /// </summary>
        /// <param name="roleID"></param>
        /// <param name="menuListID"></param>
        /// <returns></returns>
        public bool checkAuthorized(int roleID, int menuListID)
        {
            bool flag = false;
           
            try
            {
                string sql = "select * from Role_MenuList where RoleID=@roleID and MenuListID=@menuListID";

                SqlCommand cmd = new SqlCommand(sql, _connectData.GetConnect());
                cmd.Parameters.AddWithValue("@roleID", roleID);
                cmd.Parameters.AddWithValue("@menuListID", menuListID);
                DataTable dt = _connectData.GetDataTable(cmd);

                if (dt.Rows.Count > 0) {
                    flag = true;
                }
              
                cmd.Dispose();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("Error error error: " + ex.StackTrace);
                return false;
            }
            return flag;
        }
        /// <summary>
        /// get class by parent
        /// </summary>
        /// <param name="MemberID"></param>
        /// <returns></returns>
        public DataTable GetClassByParent(String MemberID)
        {
            SqlConnection con = _connectData.GetConnect();
            try
            {
                SqlCommand command = new SqlCommand("sp_ParentClass", con);
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@memberID", SqlDbType.NVarChar).Value = MemberID;

                DataTable dt = _connectData.GetDataTable(command);
                con.Dispose();
                return dt;
            }
            catch (SqlException ex)
            {
                Console.WriteLine("SQL Error" + ex.Message.ToString());
                return null;
            }
        }


        /// <summary>
        /// Load avatar of member
        /// </summary>
        /// <param name="_memberID"></param>
        internal DataRow loadAvatar(String memberID)
        {
            SqlConnection con = _connectData.GetConnect();
            SqlCommand cmd = new SqlCommand("select * from Member where MemberID = @memberID", con);
            cmd.Parameters.AddWithValue("@memberID", memberID);
            return _connectData.GetDataTable(cmd).Rows[0];
        }


        /// <summary>
        /// Update avatar
        /// </summary>
        /// <param name="maxMemID"></param>
        /// <param name="teacherAvatar"></param>
        internal void UpdateAvatar(String maxMemID, String memberAvatar)
        {
            SqlConnection con = _connectData.GetConnect();
            SqlCommand cmd = new SqlCommand("update Member set avatar = @avatar where MemberID = @memberID", con);
            cmd.Parameters.AddWithValue("@avatar", memberAvatar);
            cmd.Parameters.AddWithValue("@memberID", maxMemID);
            con.Open();
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            con.Close();
        }

        /// <summary>
        /// Get details of a admin based memberID
        /// </summary>
        /// <param name="adminID"></param>
        /// <returns></returns>
        internal DataRow GetAdminDetails(String adminID)
        {
            string sql = "select * from AdminDetailsView where MemberID = @memberID";
            SqlCommand cmd = new SqlCommand(sql, _connectData.GetConnect());
            cmd.Parameters.AddWithValue("@memberID", adminID);

            return _connectData.GetDataTable(cmd).Rows[0];
        }


        /// <summary>
        /// Update information of teacher from Teacher page
        /// </summary>
        /// <param name="memberID"></param>
        /// <param name="sex"></param>
        /// <param name="birthday"></param>
        /// <param name="address"></param>
        /// <param name="email"></param>
        /// <param name="phone"></param>
        /// <returns></returns>
        internal int UpdateAdmin(String memberID, String memberName, String fullname, String sex, String birthday, String address, String email, String phone, String pass, String career, String avatar)
        {
            try
            {
                SqlConnection con = _connectData.GetConnect();
                string sqlUp = "";
                if (pass == "")
                {
                    sqlUp = "update Member set MemberName = @memberName,"+
                                                    " FullName = @fullname, " +
                                                    " Sex = @sex, " +
                                                    " Birthday = @birthday, " +
                                                    " Address = @address, " +
                                                    " Email = @email, " +
                                                    " Phone = @phone, " +
                                                    " Career = @career, " +
                                                    " Avatar = @avatar " +
                                                    " where MemberID = @memberID ";
                }
                else
                {
                    sqlUp = "update Member set MemberName = @memberName," +
                                                    " FullName = @fullname, " +
                                                    " Sex = @sex, " +
                                                    " Birthday = @birthday, " +
                                                    " Address = @address, " +
                                                    " Email = @email, " +
                                                    " Phone = @phone, " +
                                                    " Career = @career, " +
                                                    " Pass = @pass, " +
                                                    " Avatar = @avatar " +
                                                    " where MemberID = @memberID ";
                }

                SqlCommand cmd = new SqlCommand(sqlUp, con);
                cmd.Parameters.AddWithValue("@memberName", memberName);
                cmd.Parameters.AddWithValue("@fullname", fullname);
                cmd.Parameters.AddWithValue("@sex", sex);
                cmd.Parameters.AddWithValue("@birthday", birthday);
                cmd.Parameters.AddWithValue("@address", address);
                cmd.Parameters.AddWithValue("@email", email);
                cmd.Parameters.AddWithValue("@phone", phone);
                cmd.Parameters.AddWithValue("@career", career);
                cmd.Parameters.AddWithValue("@avatar", avatar);
                cmd.Parameters.AddWithValue("@memberID", memberID);
                if (pass != "")
                {
                    string hPassword = _general.ComputeHash(pass, new SHA256CryptoServiceProvider());
                    cmd.Parameters.AddWithValue("@pass", hPassword);
                }

                con.Open();
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                con.Close();
            }
            catch (SqlException sqlEx)
            {
                System.Diagnostics.Debug.WriteLine(sqlEx.Message);
                return sqlEx.Number;
            }

            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return 0;
            }

            return 1;
        }

        /// <summary>
        /// Check pass of memeber
        /// </summary>
        /// <param name="memberID"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        internal bool CheckPass(String memberID, String pass)
        {
            string hPassword = _general.ComputeHash(pass, new SHA256CryptoServiceProvider());
            SqlConnection con = _connectData.GetConnect();
            SqlCommand cmd = new SqlCommand("select Count(*) from Member where Pass = @pass and MemberID = @memberID", con);
            cmd.Parameters.AddWithValue("@pass", hPassword);
            cmd.Parameters.AddWithValue("@memberID", memberID);

            int count = Int16.Parse(_connectData.GetDataTable(cmd).Rows[0][0].ToString());
            if (count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// Set a teacher is visible or not
        /// </summary>
        /// <param name="p"></param>
        public void SetMemberVisible(String memberID, String memberVisible)
        {
            SqlConnection con = _connectData.GetConnect();

            string sqlUp = "update Member set MemberVisible = @memberVisible " +
                                            " where MemberID = @memberID ";

            SqlCommand cmd = new SqlCommand(sqlUp, con);
            cmd.Parameters.AddWithValue("@memberVisible", memberVisible);
            cmd.Parameters.AddWithValue("@memberID", memberID);

            con.Open();
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            con.Close();

        }


        /// <summary>
        /// Get Teacher list fill by Member Visible
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public DataTable GetAdminList(String memberVisible, String memberID)
        {
            string sql = "";
            if (memberID == "1")
            {
                sql = "select MemberID, MemberName, FullName, Avatar, MemberVisible, RoleName, Birthday, RoleID from AdminDetailsView where MemberVisible = @memberVisible and RoleID <> 1";
            }
            
            else
            {
                sql = "select MemberID, MemberName, FullName, Avatar, MemberVisible, RoleName, Birthday, RoleID from AdminDetailsView where MemberVisible = @memberVisible and RoleID <> 1 and RoleID <> 2";
                
            }
            SqlCommand cmd = new SqlCommand(sql, _connectData.GetConnect());
            cmd.Parameters.AddWithValue("@memberVisible", memberVisible);
            return _connectData.GetDataTable(cmd);
        }


        /// <summary>
        /// Set role for admin web
        /// </summary>
        /// <param name="memberID"></param>
        /// <param name="rule"></param>
        internal bool SetAdminRole(String memberID, String roleID)
        {
            try
            {
                SqlConnection con = _connectData.GetConnect();

                string sqlUp = "update Member set RoleID = @roleID " +
                                                " where MemberID = @memberID ";

                SqlCommand cmd = new SqlCommand(sqlUp, con);
                cmd.Parameters.AddWithValue("@roleID", roleID);
                cmd.Parameters.AddWithValue("@memberID", memberID);

                con.Open();
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                con.Close();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// Reset default pass for teacher
        /// </summary>
        internal void ResetDefaultPass(String memberID)
        {
            string hPassword = _general.ComputeHash(ConstantClass._passwordDefault, new SHA256CryptoServiceProvider());
            SqlConnection con = _connectData.GetConnect();
            SqlCommand cmd = new SqlCommand("update Member set pass = @pass where MemberID = @memberID", con);
            cmd.Parameters.AddWithValue("@pass", hPassword);
            cmd.Parameters.AddWithValue("@memberID", memberID);
            con.Open();
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            con.Close();
        }


        /// <summary>
        /// Create Admin
        /// </summary>
        /// <param name="memberName"></param>
        /// <param name="fullname"></param>
        /// <param name="sex"></param>
        /// <param name="birthday"></param>
        /// <param name="address"></param>
        /// <param name="email"></param>
        /// <param name="phone"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        internal int CreateAdmin(String roleID, String memberName, String fullname, String sex, String birthday, String address, String email, String phone, String pass)
        {
            try
            {
                pass = _general.ComputeHash(ConstantClass._passwordDefault, new SHA256CryptoServiceProvider());
                SqlConnection con = _connectData.GetConnect();
                SqlCommand cmd = new SqlCommand("insert into Member(RoleID, MemberName, Pass, FullName, Sex, Birthday, [Address], Email, Phone) " +
                                                     "values(@roleID, @memberName, @pass, @fullname, @sex, @birthday, @address, @email, @phone)", con);

                //SqlCommand cmd = new SqlCommand("insert into Member(ClassID, RoleID, MemberName, Pass, FullName, Sex, Birthday, [Address], Email, Phone) " +
                //                                     "values(Null, @roleID, @memberName, @pass, @fullname, @sex, @birthday, @address, @email, @phone)", con);

                cmd.Parameters.AddWithValue("@roleID", roleID);
                cmd.Parameters.AddWithValue("@memberName", memberName);
                cmd.Parameters.AddWithValue("@pass", pass);
                cmd.Parameters.AddWithValue("@fullname", fullname);
                cmd.Parameters.AddWithValue("@sex", sex);
                cmd.Parameters.AddWithValue("@birthday", birthday);
                cmd.Parameters.AddWithValue("@address", address);
                cmd.Parameters.AddWithValue("@email", email);
                cmd.Parameters.AddWithValue("@phone", phone);

                con.Open();
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                con.Close();
            }
            catch (SqlException sqlEx)
            {
                System.Diagnostics.Debug.WriteLine(sqlEx.Message);
                return sqlEx.Number;
            }

            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return 0;
            }

            return 1;
        }


        /// <summary>
        /// Get Admin Permission List
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        internal DataTable GetAdminPermissionList(String roleID)
        {
            if (roleID == "1")
            {
                return _connectData.GetDataTable("select * from MemberRole where RoleID <> 3 and RoleID <> 4");
            }
            else
            {
                return _connectData.GetDataTable("select * from MemberRole where RoleID <> 1 and RoleID <> 2 and RoleID <> 3 and RoleID <> 4 ");
            }
        }


        /// <summary>
        /// Get details of a parent based memberID
        /// </summary>
        /// <param name="teacherID"></param>
        /// <returns></returns>
        public DataRow GetMemberDetails(String parentID)
        {
            string sql = "select * from Member where memberID = @parentID";
            SqlCommand cmd = new SqlCommand(sql, _connectData.GetConnect());
            cmd.Parameters.AddWithValue("@parentID", parentID);

            return _connectData.GetDataTable(cmd).Rows[0];
        }

    }
}